
let express = require('express')
let fs = require('fs')
let app = express()
app.engine('html', require('express-art-template'));
app.use('/node_modules/',express.static('./node_modules'))
app.use('/public/',express.static('./public'))
// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: false }))
     
// parse application/json
app.use(express.json())

app.get('/',function(req,res){
    fs.readFile('./public/db.json',function(err,data){
        if(err){
            return res.status(500).send('server error')
        }
      
        let comts = JSON.parse(data.toString()).comts
        res.render('index.html',{comts:comts})
    })
    
})

app.get('/sendcomment',function(req,res){
    fs.readFile('./views/edit.html',function(err,data){
        if(err){
            return res.status(500).send('server error')
        }
        res.send(data.toString())
    })
})

app.post('/postcoment',function(req,res){
    console.log(req.body);

    fs.readFile('./public/db.json',function(err,data){
        if(err){
            return res.status(500).send('server error')
        }
        let comts = JSON.parse(data.toString()).comts
        comts.push({comment:req.body.comment,name:req.body.name})
        comts = JSON.stringify({comts})
        fs.writeFile('./public/db.json',comts,function(err){
            if(err){
                console.log('写入失败');
            }
            res.redirect('/')
        })
        
        
    })

    
})



app.listen(3000,function(){
    console.log('server running...');
})